package com.changgou.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.service.WeiXinPayService;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/weixin/pay")
public class WeiXinPayController {

    @Autowired
    private WeiXinPayService weiXinPayService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    // 队列交换机信息注入
    @Value("${mq.pay.queue.order}")
    private String queue;
    @Value("${mq.pay.exchange.order}")
    private String exchange;
    @Value("${mq.pay.routing.key}")
    private String routing_key;

    /**
     * 提交订单生成支付二维码,并发送http请求调用微信的统一下单接口
     *
     * @return
     */
    @RequestMapping("/create/native")
    public Result createNative(Map<String, String> params) {
        Map map = weiXinPayService.createNative(params);
        return new Result(true, StatusCode.OK, "生成二维码成功", map);
    }

    /**
     * 查询支付状态
     *
     * @param out_trade_no
     * @return
     */
    @GetMapping(value = "/query/status")
    public Result queryStatus(String out_trade_no) {
        Map map = weiXinPayService.queryStatus(out_trade_no);
        return new Result(true, StatusCode.OK, "查询状态成功", map);
    }

    @Autowired
    private Environment environment;

    /**
     * 支付回调接口
     *
     * @param request
     * @return
     */
    @RequestMapping("/notify/url")
    public String notifyUrl(HttpServletRequest request) {
        Map<String, String> respMap;
        InputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;
        try {
            // 以流的方式返回支付状态信息
            inputStream = request.getInputStream();
            // 读取支付回调的数据
            outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            // 将支付回调的数据转换成xml字符串
            String result = new String(outputStream.toByteArray(), "utf-8");
            // 将xml字符串转换成map
            Map<String, String> resultMap = WXPayUtil.xmlToMap(result);
            System.out.println("resultMap:  " + resultMap);

            String attach = resultMap.get("attach");
            Map<String, String> map = JSON.parseObject(attach, Map.class);
            String from = map.get("from");
            switch (from) {
                case "1":
                    // 普通订单
                    rabbitTemplate.convertAndSend(exchange, routing_key, JSON.toJSONString(resultMap));
                    break;
                case "2":
                    // 秒杀订单
                    rabbitTemplate.convertAndSend(environment.getProperty("mq.pay.exchange.seckillorder"),
                            environment.getProperty("mq.pay.routing.seckillkey"),
                            JSON.toJSONString(resultMap));
                    break;
                default:
                    System.out.println("系统错误..");
                    break;
            }
            // 发送到mq
            // 设置响应数据
            respMap = new HashMap<>();
            respMap.put("return_code", "SUCCESS");
            respMap.put("return_msg", "OK");
            return WXPayUtil.mapToXml(respMap);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}
